use GD::Graph::lines;
use GD::Graph::colour;
use GD::Graph::Data;
use IO::All;
use Test::More;
require 'save.pl';

GD::Graph::colour::read_rgb("rgb.txt") or 
	die "Cannot read colours from rgb.txt";

print STDERR "Processing sample59\n";

my $file = "15SA0571RZ_L8_I328.bL20000.nB1.cn0.05.chr1.plot.txt";
my @content = io->file($file)->slurp;
map{ chomp $_; } @content;

# original data
my @x = split /\s+/, $content[0];
my $log2_smoothed = NA2undef([ split /\s+/, $content[2] ]);
my $is_sexual = 5;
my $na_region = h_annotate(\@x, [sort{$a<=>$b} split /\s+/, $content[5]], $is_sexual);
my $data_base_isna_regions = h_annotate(\@x, [sort {$a<=>$b} split /\s+/, $content[6]], $is_sexual);
my $centromere = h_annotate(\@x, [split /\s+/, $content[8]], $is_sexual);
=pod
map{
  shift @x;
  shift @{$log2_smoothed};
  shift @{$na_region};
  shift @{$data_base_isna_regions};
  shift @{$centromere};
}(0..6000);
map{
  pop @x;
  pop @{$log2_smoothed};
  pop @{$na_region};
  pop @{$data_base_isna_regions};
  pop @{$centromere};
}(0..3000);
=cut
note scalar(@x);
note scalar(@{$na_region});
note scalar(@{$data_base_isna_regions});
note scalar(@{$centromere});
note scalar(@{$log2_smoothed});

$data = [
  \@x,
  $log2_smoothed,
  $na_region,
  $data_base_isna_regions,
  $centromere,
];

$my_graph = new GD::Graph::lines();

$my_graph->set( 
	x_label => 'X Label',
	y_label => 'Y label',
	title => 'A Multiple Line Graph',
	y_max_value => 10,
	y_min_value => -5,
	y_tick_number => 3,
	y_label_skip => 1,
	zero_axis_only => 0,
	long_ticks => 0,
	x_ticks => 0,
	dclrs => [ qw( blue mediumvioletred darkturquoise black) ],
	line_types => [ 1 ],
	line_type_scale => 3,
	legend_marker_width => 10,
	line_width => 2,
  skip_undef => 1,
	show_values => 0,

	transparent => 0,

) or warn $my_graph->error;

$my_graph->set_legend( 'one' );
$my_graph->plot($data) or die $my_graph->error;
save_chart($my_graph, 'sample59');


#
#
#
sub NA2undef {
  my $array = shift;
  [map{
    $_
      ? $_ =~ /NA/
        ? undef
        : $_
      : undef;
      
  } @{$array}];
}


sub h_annotate{
  # $x: all x values
  # $position: an array ref
  # $value: y-value
  my ($x,$position,$value) = @_;
  my $x_length = scalar(@{$x});
  my $ret = [(undef)x$x_length];
  my $start_position = undef;
  for my $index (0..$#{$position}) {
    if ($index%2 == 0) {
      $start_position = $position->[$index];
    } else {
      my $end_position = $position->[$index];
      map {
        $ret->[$_-1] = $value;
      } ($start_position..$end_position)
    }
  }
  $ret;
}

